package com.atguigu.preparedstatement.crud;

import com.atguigu.bean.Customer;
import com.atguigu.bean.Order;
import com.atguigu.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * PreparedStatement 实现针对于不同表的通用的查询操作
 *
 * @author admin
 */
public class PreparedStatementQueryTest {

    @Test
    public void testGetForList() {
        String sql1 = "select id, name, email, birth from customers";
        List<Customer> customers = getForList(Customer.class, sql1);
        customers.forEach(System.out::println);

        String sql2 = "select order_id orderId, order_name orderName, order_date orderDate from `order`";
        List<Order> orders = getForList(Order.class, sql2);
        orders.forEach(System.out::println);
    }

    public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1.获取连接
            connection = JDBCUtils.getConnection();

            // 2.预编译 sql 语句，返回 PreparedStatement 实例
            preparedStatement = connection.prepareStatement(sql);

            // 3.填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            // 4.执行，并返回结果集
            resultSet = preparedStatement.executeQuery();
            // 获取结果集的元数据 ResultSetMetaData
            ResultSetMetaData rsmd = resultSet.getMetaData();
            // 通过 ResultSetMetaData 获取结果集中的列数
            int columnCount = rsmd.getColumnCount();
            // 创建集合对象
            ArrayList<T> list = new ArrayList<>();

            // 5.处理结果集
            while (resultSet.next()) {
                T t = clazz.newInstance();

                // 处理结果集一行数据中的每一列
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columnValue = resultSet.getObject(i + 1);

                    // 获取每个列的列名
                    String columnLabel = rsmd.getColumnLabel(i + 1);

                    // 给 customers 对象指定 columnName 属性，赋值为 columnValue   通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.关闭资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }

    @Test
    public void testGetInstance() {
        String sql1 = "select id, name, email from customers where id = ?";
        Customer customer1 = getInstance(Customer.class, sql1, 12);
        System.out.println(customer1);

        String sql2 = "select order_id orderId, order_name orderName, order_date orderDate from `order` where order_id = ?";
        Order order = getInstance(Order.class, sql2, 2);
        System.out.println(order);
    }

    /**
     * 针对于不同的表的通用的查询操作，返回表中的一条记录
     *
     * @param clazz
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1.获取连接
            connection = JDBCUtils.getConnection();

            // 2.预编译 sql 语句，返回 PreparedStatement 实例
            preparedStatement = connection.prepareStatement(sql);

            // 3.填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            // 4.执行，并返回结果集
            resultSet = preparedStatement.executeQuery();
            // 获取结果集的元数据 ResultSetMetaData
            ResultSetMetaData rsmd = resultSet.getMetaData();
            // 通过 ResultSetMetaData 获取结果集中的列数
            int columnCount = rsmd.getColumnCount();

            // 5.处理结果集
            if (resultSet.next()) {
                T t = clazz.newInstance();

                // 处理结果集一行数据中的每一列
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columnValue = resultSet.getObject(i + 1);

                    // 获取每个列的列名
                    String columnLabel = rsmd.getColumnLabel(i + 1);

                    // 给 customers 对象指定 columnName 属性，赋值为 columnValue   通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.关闭资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }
}
